/**
 * ALYR.NET 智能体实时规则监控器
 * 版权所有 (c) 2020-2025 ALYR.NET
 */

const chokidar = require('chokidar');
const { AlyrAIRulesChecker } = require('./ai-rules-checker');
const chalk = require('chalk');
const fs = require('fs-extra');

class AlyrRealTimeMonitor {
  constructor() {
    this.checker = new AlyrAIRulesChecker();
    this.isMonitoring = false;
  }

  // 🔍 启动实时监控
  startMonitoring() {
    if (this.isMonitoring) return;
    
    console.log(chalk.blue('🔍 启动Builder.Alyr.Net 智能体实时规则监控...'));
    
    // 项目根目录路径（.trae的上级目录）
    const projectRoot = require('path').resolve(__dirname, '../..');
    console.log(chalk.gray(`监控项目目录: ${projectRoot}`));
    
    // 监控后端文件（在项目根目录下）
    const backendWatcher = chokidar.watch([
      `${projectRoot}/server/**/*`, 
      `${projectRoot}/backend/**/*`
    ], {
      ignored: /node_modules/,
      persistent: true
    });
    
    // 监控前端文件（在项目根目录下）
    const frontendWatcher = chokidar.watch([
      `${projectRoot}/src/**/*`, 
      `${projectRoot}/client/**/*`, 
      `${projectRoot}/frontend/**/*`
    ], {
      ignored: /node_modules/,
      persistent: true
    });
    
    // 后端文件事件处理
    backendWatcher
      .on('add', (path) => this.handleBackendFileAdd(path))
      .on('change', (path) => this.handleFileChange(path));
    
    // 前端文件事件处理
    frontendWatcher
      .on('add', (path) => this.handleFrontendFileAdd(path))
      .on('change', (path) => this.handleFileChange(path));
    
    this.isMonitoring = true;
    console.log(chalk.green('✅ 实时监控已启动'));
  }

  // 🔥 处理后端文件添加
  async handleBackendFileAdd(filePath) {
    console.log(chalk.yellow(`🔍 检测到后端文件: ${filePath}`));
    
    const fileName = require('path').basename(filePath);
    
    // 读取项目配置获取当前后端前缀
    let currentPrefix = 'Alyr'; // 默认前缀
    try {
      const configPath = require('path').resolve(__dirname, '../project_rules.md');
      if (fs.existsSync(configPath)) {
        const configContent = fs.readFileSync(configPath, 'utf8');
        const prefixMatch = configContent.match(/后端前缀:\s*([^\s\(]+)/);
        if (prefixMatch) {
          currentPrefix = prefixMatch[1];
        }
      }
    } catch (error) {
      console.log(chalk.gray(`使用默认前缀: ${currentPrefix}`));
    }
    
    // 动态构建正则表达式：支持当前配置的前缀
    const prefixPattern = new RegExp(`^${currentPrefix}-[a-zA-Z][a-zA-Z0-9]*\\.(service|controller|module|entity|dto|guard|interceptor|pipe|filter|middleware|resolver|repository)?\\.(ts|js)$|^${currentPrefix}-[a-zA-Z][a-zA-Z0-9]*\\.spec\\.ts$`);
    const isValidName = prefixPattern.test(fileName);
    
    if (!isValidName) {
      console.log(chalk.red(`⚠️ 后端文件命名违规: ${filePath}`));
      console.log(chalk.yellow(`📋 处理选项:`));
      console.log(chalk.yellow(`   1. 删除文件: ${fileName}`));
      console.log(chalk.yellow(`   2. 修复文件: 重命名为 ${currentPrefix}-${fileName}`));
      console.log(chalk.cyan(`💡 建议: 运行一键项目设置.bat强制同步所有后端前缀`));
      
      // 发送安全警报但不直接删除
      this.sendSecurityAlert(`后端文件命名违规: ${fileName} - 需要${currentPrefix}-前缀`);
      return;
    }
    
    // 检查版权声明
    setTimeout(async () => {
      const hasCopyright = await this.checker.validateCopyright(filePath);
      if (!hasCopyright) {
        console.log(chalk.yellow(`⚠️ 后端文件缺少版权声明: ${filePath}`));
        console.log(chalk.yellow(`📋 处理选项:`));
        console.log(chalk.yellow(`   1. 删除文件: ${fileName}`));
        console.log(chalk.yellow(`   2. 修复文件: 自动添加版权声明`));
        console.log(chalk.cyan(`💡 建议: 点击修复按钮自动添加版权声明`));
        
        this.sendSecurityAlert(`后端文件缺少版权声明: ${fileName} - 需要添加ALYR.NET版权`);
      } else {
        console.log(chalk.green(`✅ 后端文件规范检查通过: ${fileName}`));
      }
    }, 1000);
  }

  // ✅ 处理前端文件添加
  async handleFrontendFileAdd(filePath) {
    console.log(chalk.cyan(`🔍 检测到前端文件: ${filePath}`));
    
    // 检查是否使用了禁用的组件库
    if (filePath.endsWith('.tsx') || filePath.endsWith('.jsx')) {
      setTimeout(async () => {
        const isValidAntd = await this.checker.validateAntdUsage(filePath);
        if (!isValidAntd) {
          console.log(chalk.red(`❌ 前端组件库违规: ${filePath}`));
        }
      }, 1000);
    }
  }

  // 📝 处理文件修改
  async handleFileChange(filePath) {
    // 检查any类型使用
    if (filePath.endsWith('.ts') || filePath.endsWith('.tsx')) {
      const isValidType = await this.checker.validateNoAnyType(filePath);
      if (!isValidType) {
        console.log(chalk.red(`⚠️ 检测到any类型使用: ${filePath}`));
      }
    }
  }

  // 🚨 发送安全警报
  sendSecurityAlert(message) {
    const timestamp = new Date().toISOString();
    const alertMessage = `[${timestamp}] 🚨 Builder.Alyr.Net 安全警报: ${message}`;
    
    console.log(chalk.red.bold(alertMessage));
    
    // 记录到安全日志
    fs.appendFileSync('.trae/logs/security.log', alertMessage + '\n');
  }

  // 🛑 停止监控
  stopMonitoring() {
    this.isMonitoring = false;
    console.log(chalk.blue('🛑 实时监控已停止'));
  }
}

// 🚀 启动监控
function startRealTimeMonitor() {
  const monitor = new AlyrRealTimeMonitor();
  monitor.startMonitoring();
  
  // 优雅退出处理
  process.on('SIGINT', () => {
    console.log(chalk.yellow('\n🛑 正在停止监控...'));
    monitor.stopMonitoring();
    process.exit(0);
  });
  
  return monitor;
}

module.exports = {
  AlyrRealTimeMonitor,
  startRealTimeMonitor
};

// 如果直接运行此脚本
if (require.main === module) {
  startRealTimeMonitor();
}